package com.fh.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fh.config.IndexImgClient;
import com.fh.model.IndexImg;
import com.fh.service.IndexImgService;
import com.fh.utils.ResultState;
import com.fh.vo.ResultVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class IndexImgServiceImpl  implements IndexImgService {


    @Resource
    private ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IndexImgClient indexImgClient;
     
    
    @Override
    public ResultVo query() {
        List<IndexImg> list = null;
        try {
            //从redis中取出的数据
            String indexImg = stringRedisTemplate.boundValueOps("indexImg").get();
            if (indexImg != null) {
                //从redis中取出的数据返回前台
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, IndexImg.class);
                list = objectMapper.readValue(indexImg, javaType);
                System.out.println("进入redis");
            } else {
                synchronized (this) {
                    String aa = stringRedisTemplate.boundValueOps("indexImg").get();
                    if (aa == null) {
                        System.out.println("进入数据库");
                        //从数据库查询返回前台和放到redis中
                        list = indexImgClient.query();
                        if (list==null){
                            List list1=new ArrayList();
                            stringRedisTemplate.boundValueOps("indexImg").set(objectMapper.writeValueAsString(list1));
                        }else {
                            stringRedisTemplate.boundValueOps("indexImg").set(objectMapper.writeValueAsString(list));
                        }

                    } else {
                        System.out.println("进入redis");
                        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, IndexImg.class);
                        list = objectMapper.readValue(aa, javaType);
                    }
                }
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (list != null) {
            return new ResultVo(ResultState.OK, "ok", list);
        } else {
            return new ResultVo(ResultState.NO, "ok", null);
        }


    }
}
